package com.ruoyi.framework.netty;

import com.ruoyi.framework.netty.childhandler.auth.AuthStrategyHandler;
import com.ruoyi.framework.netty.childhandler.chat.SingleChatHandler;
import com.ruoyi.framework.netty.childhandler.heart.HeartBeatHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * 工作线程处理初始化类，设置管道的职责链
 * @author zhusy
 * @since 2021/11/21
 */
public class NettyServerInitializer extends ChannelInitializer<NioSocketChannel> {

    /**
     * 一旦Channel被注册，这个方法就会被调用。
     * 方法返回后，该实例将从Channel的ChannelPipeline中移除。
     * @param ch
     * @throws Exception
     */
    @Override
    protected void initChannel(NioSocketChannel ch) throws Exception {
        //获取pipeline管道
        ChannelPipeline channelPipeline = ch.pipeline();
        //1、添加用于支持http协议
        //前端项目使用websocket 基于http协议，添加http编解码器
        channelPipeline.addLast(new HttpServerCodec());
        //对httpMessage进行聚合， 聚合成FullHttpRequest或FullHttpResponse
        channelPipeline.addLast(new HttpObjectAggregator(1024 * 64));
        channelPipeline.addLast(new HttpContentCompressor()); // HttpContent 压缩
        //对写大数据流的支持
        channelPipeline.addLast(new ChunkedWriteHandler());
        //权限校验与业务转发
        channelPipeline.addLast(AuthStrategyHandler.getInstance);
        //心跳检测
        channelPipeline.addLast(new HeartBeatHandler());
        //单聊业务
//        channelPipeline.addLast(SingleChatHandler.getInstance);

        //3、支持httpWebsocket
        /**
         * websocket服务器处理的协议， 用于指定给客户端链接访问的路由
         * 处理握手动作：handshaking(close, ping, pong) ping + pong = 心跳
         * 对于websocket来讲，都是以frames（帧）进行传输的，不同的数据类型对应不同的frames
         */
        //channelPipeline.addLast(new WebSocketServerProtocolHandler(SpringUtil.getBean(NettyChatProperties.class).getWebsocketUrl()));
//        //自定义的聊天处理handler
//        channelPipeline.addLast(new ChatHandler());

        //自定义的聊天处理handler
        //channelPipeline.addLast(new WsServerHandler());
    }

}
